const { ccclass, property } = cc._decorator;

@ccclass
export class Piece extends cc.Component {

    @property(cc.Texture2D)
    private texture: cc.Texture2D = null;
    //oriCol:初始图片的列编号;oriRow:初始图片的行编号;curCol:现在图片的列编号;curRow:现在图片的行编号
    public oriCol: number;
    public oriRow: number;
    public curCol: number;
    public curRow: number;
    //判断是否是空白格
    public isBlank: boolean;
    //设置isRight()状态会返回现在图片位置与初始图片位置相符
    public get isRight() {
        return this.curCol === this.oriCol && this.curRow === this.oriRow;
    }

    public init(col: number, row: number, colNum: number, colWidth: number) {
        //将col列编号和row行编号数值分别赋值给oriCol初始列编号/curCol现在列编号和oriRow初始行编号/curRow现在行编号
        this.oriCol = col;
        this.oriRow = row;
        this.curCol = col;
        this.curRow = row;
        //设置sprite节点,令其为有Sprite组件的node节点
        let sprite = this.node.addComponent(cc.Sprite);
        sprite.spriteFrame = new cc.SpriteFrame(this.texture);
        //声明rect为获取sprite节点下spriteFrame图片的矩形区域大小
        let rect = sprite.spriteFrame.getRect();
        //声明newRectWidth是sprite节点下spriteFrame图片区域的宽除以图片数量
        let newRectWidth = rect.width / colNum;
        //声明newRectHeight是sprite节点下spriteFrame图片区域的高除以图片数量
        let newRectHeight = rect.height / colNum;
        //给newRectX/newRectY赋值
        let newRectX = col * newRectWidth;
        let newRectY = (colNum - row - 1) * newRectHeight;
        //用(newRectX, newRectY, newRectWidth, newRectHeight)创建新的矩形newRect
        let newRect = cc.rect(newRectX, newRectY, newRectWidth, newRectHeight);
        //将新的矩形newRect设置入sprite节点下spriteFrame属性中
        sprite.spriteFrame.setRect(newRect);
        //设置节点的宽和高均为sprite.spriteFrame
        this.node.width = colWidth;
        this.node.height = colWidth;
        //当图格进行至右下角时设为空白格
        this.isBlank = this.oriCol === colNum - 1 && this.oriRow === 0;
        //判断当所有图格完成初始化,改变node节点的激活状态为关闭
        if (this.isBlank) {
            this.node.active = false;
        }
    }

}